package com.bsj.pay.controller.admin;

import java.io.InputStream;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.ss.usermodel.Cell;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.bsj.pay.common.ChargeOrder;
import com.bsj.pay.common.Result;
import com.bsj.pay.model.AccountBean;
import com.bsj.pay.model.AreaBean;
import com.bsj.pay.model.ChargeAccountBean;
import com.bsj.pay.model.IpPoolBean;
import com.bsj.pay.model.UserBean;
import com.bsj.pay.service.AccountService;
import com.bsj.pay.service.IpPoolService;
import com.bsj.pay.service.LogService;
import com.bsj.pay.service.impl.OrderServiceImpl;
import com.bsj.pay.util.ResultUtil;
import com.bsj.pay.util.SpringUtil;
import com.bsj.pay.util.excel.ExcelUtil;
import com.bsj.pay.util.platform.PlatformInterface;
import com.bsj.pay.util.platform.wsgw.WsgwUtil;
import com.bsj.pay.util.security.PassWrodsCreater;
import com.github.pagehelper.PageInfo;
 
@RequestMapping("/admin/account")
@Controller("adminAccountController")
public class AccountController {
	private static final Logger log = LogManager.getLogger(AccountController.class);
	
	@Autowired
	private AccountService accountService;
	
	@Autowired
	private LogService logService;
	
	@Autowired
	private IpPoolService ipPoolService;
	
	@ResponseBody
	@RequestMapping(value = "/list.html")
	public Map list(HttpServletRequest req, HttpServletResponse res,int page,int limit,AccountBean account) {
		logService.addLog(req, "查看账号列表,第"+page+"页");
		AccountBean queryModel=new AccountBean();
		if(account.getId()!=null)queryModel.setId(account.getId());
		if(!StringUtils.isEmpty(account.getAccount()))queryModel.setAccount(account.getAccount());
		if(!StringUtils.isEmpty(account.getOperator()))queryModel.setOperator(account.getOperator());
		if(account.getStatus()!=null)queryModel.setStatus(account.getStatus());
		if(account.getLogin_status()!=null)queryModel.setLogin_status(account.getLogin_status());
		PageInfo<AccountBean> pageInfo=accountService.pageList(queryModel, page, limit);
		return ResultUtil.getQuerySuccessResult(pageInfo);
	}
	
	
	@RequestMapping("/listPage.html")
    public ModelAndView listPage(HttpServletRequest request,HttpServletResponse response,ModelAndView mav,String operator) {
		mav.addObject("operator", operator);
		mav.setViewName("admin/account/list");
		return mav;
    }
	
	@RequestMapping("/addPage.html")
    public ModelAndView addPage(HttpServletRequest request,HttpServletResponse response,ModelAndView mav,String operator) {
		mav.addObject("operator", operator);
		mav.setViewName("admin/account/add");
		return mav;
    }
	
	@ResponseBody
	@RequestMapping(value = "/remove.html")
	public Result remove(HttpServletRequest req, HttpServletResponse res,Long id) {
		Result result=new Result();
		try {
			if(accountService.removeById(id)>0)
			{
				result.setCode(0);
				result.setMsg("删除成功");
				logService.addLog(req, "删除账号,ID:"+id);
			}
			else
			{
				result.setCode(1);
				result.setMsg("删除失败");
			}
			
			return result;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			result.setCode(500);
			result.setMsg(e.getMessage());
			return result;
		}

	}
	
	@ResponseBody
	@RequestMapping(value = "/updateStatus.html")
	public Result updateStatus(HttpServletRequest req, HttpServletResponse res,Long id,Integer status) {
		Result result=new Result();
		try {
			AccountBean account=new AccountBean();
			account.setId(id);
			account.setStatus(status==0?1:0);
			if(accountService.update(account)>0)
			{
				result.setCode(0);
				result.setMsg("修改成功");
			}
			else
			{
				result.setCode(1);
				result.setMsg("修改失败");
			}
			
			return result;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			result.setCode(500);
			result.setMsg(e.getMessage());
			return result;
		}

	}
	
	
	@ResponseBody
	@RequestMapping("/add.html")
	public Result add(HttpServletRequest request,HttpServletResponse response,ModelAndView mav,AccountBean account)
	{
		UserBean user=(UserBean) request.getSession().getAttribute("auser");
		Result result=new Result();
		try {
			AccountBean queryModel=new AccountBean();
			queryModel.setAccount(account.getAccount());
			if(accountService.count(queryModel)>0)
			{
				result.setCode(1);
				result.setMsg("账号已存在，添加失败!");
				return result;
			}
			OrderServiceImpl.lastActiveTime=System.currentTimeMillis()/1000;
			/*IpPoolBean ipPool = ipPoolService.getOneCanUseIp();
			if (ipPool == null) {
				throw new Exception("代理IP不足，请重试!");
			}
			log.info("登录,账号:{},使用代理,IP:{},Port:{}",account.getAccount(),ipPool.getIp(),ipPool.getPort());
			PlatformInterface inf=(PlatformInterface) SpringUtil.getBean(account.getOperator()+"Util");
			account.setProxy_ip(ipPool.getIp());
			account.setProxy_port(ipPool.getPort());
			account.setProxy_expire_time(ipPool.getExpire_time());
			Map<String,String> resultMap=inf.login(account);
			account.setToken(resultMap.get("token"));
			account.setInfo(resultMap.get("userId"));*/
			account.setCreate_time(System.currentTimeMillis()/1000);
			account.setCreate_user(user.getId());
			accountService.insert(account);

			logService.addLog(request, "新增"+account.getOperator()+"账号:"+account.getAccount());
			result.setCode(0);
			result.setMsg("添加成功");
			return result;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			result.setCode(1);
			result.setMsg(e.getMessage());
			return result;
		}
		
	}
	
	@RequestMapping("/updatePage.html")
	public ModelAndView updatePage(HttpServletRequest request, HttpServletResponse response, HttpSession session,ModelAndView mav,Long id) {
		mav.addObject("account", accountService.getById(id));
		mav.setViewName("admin/account/update");
		return mav;
	}
	
	@ResponseBody
	@RequestMapping(value = "/update.html")
	public Result update(HttpServletRequest req, HttpServletResponse res,AccountBean account) {
		Result result=new Result();
		try {
			accountService.update(account);
			result.setCode(0);
			result.setMsg("修改成功");
			return result;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			result.setCode(500);
			result.setMsg(e.getMessage());
			return result;
		}

	}
	
	@ResponseBody
	@RequestMapping(value = "/batchResetBindFailCount.html")
	public Result batchResetBindFailCount(HttpServletRequest req, HttpServletResponse res,String operator) {
		Result result=new Result();
		try {
			int count=accountService.batchResetBindFailCount(operator);
			logService.addLog(req, "重置所有账号绑定次数,类型："+operator);
			result.setCode(0);
			result.setMsg("重置"+count+"条数据");
			return result;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			result.setCode(1);
			result.setMsg(e.getMessage());
			return result;
		}

	}
	
	@ResponseBody
	@RequestMapping(value = "/removeAll.html")
	public Result removeAll(HttpServletRequest req, HttpServletResponse res,String operator) {
		Result result=new Result();
		try {
			int count=accountService.removeAll(operator);
			logService.addLog(req, "删除所有账号,类型："+operator);
			result.setCode(0);
			result.setMsg("删除"+count+"条数据");
			return result;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			result.setCode(1);
			result.setMsg(e.getMessage());
			return result;
		}

	}
	
	@RequestMapping("/loginPage.html")
	public ModelAndView loginPage(HttpServletRequest request, HttpServletResponse response,ModelAndView mav,Long id, String operator) {
		mav.addObject("account", accountService.getById(id));
		mav.addObject("operator", operator);
		mav.setViewName("admin/account/login");
		return mav;
	}
	
	@ResponseBody
	@RequestMapping("/reLogin.html")
	public Result reLogin(HttpServletRequest request,HttpServletResponse response,ModelAndView mav,Long id)
	{
		Result result=new Result();
		try {
			AccountBean updateModel=new AccountBean();
			updateModel.setId(id);
			updateModel.setLogin_status(0);
			accountService.update(updateModel);
			OrderServiceImpl.lastActiveTime=System.currentTimeMillis()/1000;
			result.setCode(0);
			result.setMsg("操作成功");
			return result;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			result.setCode(1);
			result.setMsg(e.getMessage());
			return result;
		}
		
	}
	
	@ResponseBody
	@RequestMapping("/login.html")
	public Result login(HttpServletRequest request,HttpServletResponse response,ModelAndView mav,AccountBean account)
	{
		UserBean user=(UserBean) request.getSession().getAttribute("auser");
		Result result=new Result();
		try {
			AccountBean queryModel=new AccountBean();
			queryModel.setAccount(account.getAccount());
			if(accountService.count(queryModel)>0)
			{
				result.setCode(1);
				result.setMsg("账号已存在!");
				return result;
			}
			OrderServiceImpl.lastActiveTime=System.currentTimeMillis()/1000;
			IpPoolBean ipPool = ipPoolService.getOneCanUseIp();
			if (ipPool == null) {
				throw new Exception("代理IP不足，请重试!");
			}
			log.info("登录,账号:{},使用代理,IP:{},Port:{}",account.getAccount(),ipPool.getIp(),ipPool.getPort());
			PlatformInterface inf=(PlatformInterface) SpringUtil.getBean(account.getOperator()+"Util");
			account.setProxy_ip(ipPool.getIp());
			account.setProxy_port(ipPool.getPort());
			account.setProxy_expire_time(ipPool.getExpire_time());
			Map<String,String> resultMap=inf.login(account);
			account.setInfo(resultMap.get("userId"));
			account.setLogin_cookie(resultMap.get("token"));
			account.setCreate_time(System.currentTimeMillis()/1000);
			account.setCreate_user(user.getId());
			account.setQuota(1000000);
			accountService.insert(account);
			
			/*AccountBean updateModel=new AccountBean();
			updateModel.setId(account.getId());
			updateModel.setLogin_status(1);
			updateModel.setProxy_ip(ipPool.getIp());
			updateModel.setProxy_port(ipPool.getPort());
			updateModel.setProxy_expire_time(ipPool.getExpire_time());
			updateModel.setUpdate_time(System.currentTimeMillis()/1000);
			accountService.update(updateModel);*/
			
			logService.addLog(request, "新增"+account.getOperator()+"账号:"+account.getAccount());
			result.setCode(0);
			result.setMsg("添加成功");
			return result;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			result.setCode(1);
			result.setMsg(e.getMessage());
			return result;
		}
		
	}
	
	@RequestMapping("/onlineOrderListPage.html")
	public ModelAndView onlineOrderListPage(HttpServletRequest request,HttpServletResponse response,ModelAndView mav,Long id) {
		mav.setViewName("admin/account/onlineOrderList");
		mav.addObject("id",id);
		return mav;
	}

	@ResponseBody
	@RequestMapping("/onlineOrderList.html")
	public Map onlineOrderList(HttpServletRequest req,HttpServletResponse res,int page,int limit,Long id) throws Exception {
		AccountBean account = accountService.getById(id);
		List<ChargeOrder> onlineOrderList=null;
		try {
			OrderServiceImpl.lastActiveTime=System.currentTimeMillis()/1000;
			PlatformInterface inf=(PlatformInterface) SpringUtil.getBean(account.getOperator()+"Util");
			onlineOrderList = inf.queryTransList(account, page, limit);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			if(e.getMessage().contains("网络链接失败"))
 			{
 				accountService.addProxyFailTimes(account.getId());
 			}
			else if(e.getMessage().contains("请重新登录"))
			{
				AccountBean updateModel=new AccountBean();
            	updateModel.setId(account.getId());
            	updateModel.setLogin_status(2);
            	updateModel.setLogin_cookie("");
            	updateModel.setUpdate_time(System.currentTimeMillis()/1000);
                accountService.update(updateModel);
			}
		}
		AccountBean updateAccount=new AccountBean();
		updateAccount.setId(id);
		updateAccount.setBuy_last_time(System.currentTimeMillis()/1000);
		accountService.update(updateAccount);
		PageInfo<ChargeOrder> pageInfo = new PageInfo(onlineOrderList);
		pageInfo.setPageNum(page);
		pageInfo.setPageSize(limit);
		if(onlineOrderList!=null)pageInfo.setTotal(onlineOrderList.size());
		return ResultUtil.getQuerySuccessResult(pageInfo);
	}
	
	@ResponseBody
	@RequestMapping("/importAccountCK.html")
	public Result importAccountCK(HttpServletRequest req,HttpServletResponse res,@RequestParam MultipartFile file) {
		Result result = new Result();
		try {
			String operator=req.getParameter("operator");
			UserBean user=(UserBean) req.getSession().getAttribute("auser");
			InputStream inputStream = file.getInputStream();
			List<List<Cell>> list = ExcelUtil.getBankListByExcel(inputStream,file.getOriginalFilename());
			inputStream.close();
			int num = 0;
			for (int i = 0; i < list.size(); ++i) {
				try {
					List<Cell> lo = list.get(i);
					String account = ExcelUtil.getStringValueFromCell((Cell) lo.get(0));
					String cookies = ExcelUtil.getStringValueFromCell((Cell) lo.get(1));
					if(!StringUtils.isEmpty(account)&&!StringUtils.isEmpty(cookies)) {
						account=account.trim();
						cookies=cookies.trim();
						AccountBean addModel=new AccountBean();
						addModel.setAccount(account);
						if(accountService.count(addModel)>0){
							continue;
						}
						addModel.setQuota(1000000);
						addModel.setOperator(operator);
						addModel.setLogin_cookie(cookies);
						addModel.setCreate_time(System.currentTimeMillis()/1000);
						addModel.setCreate_user(user.getId());
						accountService.insert(addModel);
						num++;
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					continue;
				}
			}
			if(num>0)OrderServiceImpl.lastActiveTime=System.currentTimeMillis()/1000;
			result.setCode(0);
			result.setMsg("上传成功,上传" + num + "条数据");
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			result.setCode(500);
			result.setMsg("上传失败" + e.getMessage());
			return result;
		}
	}
	
	@ResponseBody
	@RequestMapping("/importAccount.html")
	public Result importAccount(HttpServletRequest req,HttpServletResponse res,@RequestParam MultipartFile file) {
		Result result = new Result();
		try {
			String operator=req.getParameter("operator");
			UserBean user=(UserBean) req.getSession().getAttribute("auser");
			InputStream inputStream = file.getInputStream();
			List<List<Cell>> list = ExcelUtil.getBankListByExcel(inputStream,file.getOriginalFilename());
			inputStream.close();
			int num = 0;
			for (int i = 0; i < list.size(); ++i) {
				try {
					List<Cell> lo = list.get(i);
					String account = ExcelUtil.getStringValueFromCell((Cell) lo.get(0));
					String password = ExcelUtil.getStringValueFromCell((Cell) lo.get(1));
					if(!StringUtils.isEmpty(account)&&!StringUtils.isEmpty(password)) {
						account=account.trim();
						password=password.trim();
						AccountBean addModel=new AccountBean();
						addModel.setAccount(account);
						if(accountService.count(addModel)>0){
							continue;
						}
						addModel.setQuota(1000000);
						addModel.setOperator(operator);
						addModel.setPassword(password);
						addModel.setCreate_time(System.currentTimeMillis()/1000);
						addModel.setCreate_user(user.getId());
						accountService.insert(addModel);
						num++;
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					continue;
				}
			}
			if(num>0)OrderServiceImpl.lastActiveTime=System.currentTimeMillis()/1000;
			result.setCode(0);
			result.setMsg("上传成功,上传" + num + "条数据");
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			result.setCode(500);
			result.setMsg("上传失败" + e.getMessage());
			return result;
		}
	}
}
